package util

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"zhejianglab/gin-apiserver/model/request"
	"zhejianglab/gin-apiserver/pkg/logger"
	"zhejianglab/gin-apiserver/pkg/setting"
)

// DoRequest2 sends request with given HTTP method and data and returns the response object.
func DoRequestAlarm(method, url, token string, data request.AlarmRequest) (*request.ResposeByAlarmCenter, error) {

	// Create a new request using http
	requestBody, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest(method, url, bytes.NewBuffer(requestBody))
	if err != nil {
		return nil, err
	}

	// add authorization header to the req
	req.Header.Add("Authorization", token)
	req.Header.Set("Content-type", "application/json")

	// Send req using http Client
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		logger.Log.Info(fmt.Sprintf("Error on response.", err))
		return nil, err
	}

	body, _ := ioutil.ReadAll(resp.Body)

	respose := request.ResposeByAlarmCenter{
		Success:   false,
		Code:      0,
		Message:   "",
		Data:      request.Data{},
		Timestamp: "",
	}
	err = json.Unmarshal(body, &respose)
	if err != nil {
		fmt.Print(err)
	}

	return &respose, nil
}

func GetToken() (*request.ResposeByAlarmCenter, error) {
	UserInfo := &request.AlarmUserInfo{
		UserName: setting.AlarmUserName,
		PassWord: setting.AlarmPassWord,
	}
	// Create a new request using http
	requestBody, err := json.Marshal(UserInfo)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest("POST", setting.TokenURL, bytes.NewBuffer(requestBody))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-type", "application/json")

	// Send req using http Client
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		logger.Log.Info(fmt.Sprintf("Error on response.", err))
		return nil, err
	}

	body, _ := ioutil.ReadAll(resp.Body)

	respose := request.ResposeByAlarmCenter{
		Success:   false,
		Code:      0,
		Message:   "",
		Data:      request.Data{Token: ""},
		Timestamp: "",
	}
	err = json.Unmarshal(body, &respose)
	if err != nil {
		fmt.Print(err)
	}
	return &respose, nil

}
